//
//  SNSortFriendVc.m
//  project
//
//  Created by 黄建华 on 2019/1/7.
//  Copyright © 2019年 黄建华. All rights reserved.
//

#import "SNSortFriendVc.h"
#import "SortFriendListCell.h"
#import "SortStepView.h"
#import "SortSleepDetailView.h"
#import "SortSleepView.h"

@interface SNSortFriendVc ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) UIView *view1;
@property (nonatomic, strong) UIView *view2;
@property (nonatomic, strong) UIView *view3;
@property (nonatomic, strong) UIView *view4;
@property (nonatomic, strong) UILabel *label2;

@property (nonatomic, strong) SortStepView *stepView;
@property (nonatomic, strong) SortSleepDetailView *sleepView;

@property (nonatomic, strong) SortSleepView *sleepInfoView1;
@property (nonatomic, strong) SortSleepView *sleepInfoView2;

@end

@implementation SNSortFriendVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = BBIGSTATECOLOR;
    
    UIView *stateView = [[UIView alloc] init];
    stateView.backgroundColor = BBIGSTATECOLOR;
    if (KK_ShareData.ipx)
    {
        stateView.frame = SNFRAME(0, 0, HHHWIDTH, 40 +44);
    }
    else
    {
        stateView.frame = SNFRAME(0, 0, HHHWIDTH, 20 +44);
    }
    [self.view addSubview:stateView];
    
    _sbTitleLable = [[UILabel alloc] init];
    _sbTitleLable.textAlignment = NSTextAlignmentCenter;
    _sbTitleLable.frame = SNFRAME(0, FitSimpleIpx(32, 52), HHHWIDTH, 20);
    _sbTitleLable.text = SN_Text(@"健康日报");
    _sbTitleLable.adjustsFontSizeToFitWidth = YES;
    _sbTitleLable.textColor = [UIColor whiteColor];
    _sbTitleLable.font = SNFONT(17.0);
    [self.view addSubview:_sbTitleLable];
    
    _leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _leftButton.frame = SNFRAME(5, FitSimpleIpx(0, 20), 44, 44);
    [_leftButton  setImageNormal:@"进入白"];
    [_leftButton setTitleColor:SNCOLORBLACK forState:UIControlStateNormal];
    _leftButton.titleLabel.font = SNSFONT(15.0);
    _leftButton.center = CGPointMake(25, _sbTitleLable.center.y);
    [_leftButton  addTarget:self
                     action:@selector(functionSetLeft)
           forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_leftButton];
    
    UIImageView *shadowLine = [[UIImageView alloc] init];
    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44 -2, HHHWIDTH, 2);
    shadowLine.image = [UIImage image:@"lineImage"];
//    [self.view addSubview:shadowLine];
    
    _tableView                              = [[UITableView alloc]initWithFrame:CGRectMake(0,shadowLine.bottom, HHHWIDTH,(HHHHEIGHT- shadowLine.bottom)) style:UITableViewStylePlain];
    _tableView.delegate                     = self;
    _tableView.dataSource                   = self;
    _tableView.separatorStyle               = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = SNCOLORGRAYLINE;
    
    _headView = [[UIView alloc] init];
    _headView.frame = SNFRAME(0, 0,HHHWIDTH, HHHHEIGHT *0.25);

    _footView = [[UIView alloc] init];
    _footView.frame = SNFRAME(0, 0, HHHWIDTH, HHHHEIGHT*2 +10);
    _tableView.tableFooterView = _footView;
    
    _dataArray = [NSMutableArray array];
    
    _tableView.tableHeaderView = _headView;
    _headView.backgroundColor = SNCOLORBLACK;
//    _footView.backgroundColor = SNCOLORBLACK;
    
    CGFloat width = _headView.height/2.0 - 30;
    
    UIImageView *headImageView = [[UIImageView alloc] init];
    headImageView.frame = SNFRAME(HHHWIDTH/2 - width/2.0, 10, width, width);
    headImageView.layer.cornerRadius = width/2.0;
    headImageView.layer.masksToBounds = YES;
    [_headView addSubview:headImageView];

    if (SN_USER.portrait.length > 0) {
        headImageView.image = SN_USER.headImage;
    } else {
        headImageView.image = [UIImage imageNamed:@"loginhead"];
    }
    
    
    _label2 = [UILabel simpleWithRect:SNFRAME(HHHWIDTH/3,_headView.height/2.0 - 8, HHHWIDTH/3, 30) withAlignment:NSTextAlignmentCenter withFontSize:16 withText:@"0 " withTextColor:[UIColor whiteColor]];
    [_headView addSubview:_label2];
    
    UILabel *label1 = [UILabel simpleWithRect:SNFRAME(_label2.left -90,_headView.height/2.0 +12,80, 20) withAlignment:NSTextAlignmentCenter withFontSize:14 withText:@"1 " withTextColor:[UIColor whiteColor]];
    [_headView addSubview:label1];
    
    UILabel *label3 = [UILabel simpleWithRect:SNFRAME(_label2.right +10,label1.top, 80, 20) withAlignment:NSTextAlignmentCenter withFontSize:14 withText:@"3 " withTextColor:[UIColor whiteColor]];
    [_headView addSubview:label3];
    
    UILabel *unit1 = [UILabel simpleWithRect:SNFRAME(label1.left, label1.bottom -2, label1.width, 20) withAlignment:NSTextAlignmentCenter withFontSize:13 withText:SN_Text(@"千米") withTextColor:[UIColor whiteColor]];
    [_headView addSubview:unit1];
    
    UILabel *unit2 = [UILabel simpleWithRect:SNFRAME(_label2.left, _label2.bottom, _label2.width, 20) withAlignment:NSTextAlignmentCenter withFontSize:15 withText:SN_Text(@"我的亲友排名") withTextColor:[UIColor whiteColor]];
    unit2.adjustsFontSizeToFitWidth = YES;
    [_headView addSubview:unit2];
    
    UILabel *unit3 = [UILabel simpleWithRect:SNFRAME(label3.left, label3.bottom -2, label3.width, 20) withAlignment:NSTextAlignmentCenter withFontSize:13.0 withText:SN_Text(@"步数") withTextColor:[UIColor whiteColor]];
    [_headView addSubview:unit3];
    
    UILabel *info1 = [UILabel simpleWithRect:SNFRAME(15, _headView.bottom - 23, 120, 20) withAlignment:NSTextAlignmentLeft withFontSize:13.0 withText:SN_Text(@"排行") withTextColor:[UIColor whiteColor]];
    [_headView addSubview:info1];
    
    UILabel *info2 = [UILabel simpleWithRect:SNFRAME(HHHWIDTH - 135, _headView.bottom - 23, 120, 20) withAlignment:NSTextAlignmentRight withFontSize:13.0 withText:SN_Text(@"步数") withTextColor:[UIColor whiteColor]];
    [_headView addSubview:info2];
    
    CGFloat distances = SN_PublicClass.todaySport.distance *1.0;
    label1.text = SN_USER.isMetricSystem ?[NSString stringWithFormat:@"%.2f ", roundf(1.0*distances*0.0006214*100)/100] : [NSString stringWithFormat:@"%.2f ", 1.0* distances/1000];
    
    unit1.text = SN_USER.isMetricSystem ? SN_Text(@"英里"):SN_Text(@"千米");
    
    label3.text = [NSString stringWithFormat:@"%d ",SN_PublicClass.todaySport.step];
    
    //赋值
    label1.attributedText = [self addattribtDic:label1.text];
    _label2.attributedText = [self addattribtDic:_label2.text];
    label3.attributedText = [self addattribtDic:label3.text];
    
    // 步数排行
    for (int i = 0 ; i < 4; i++) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        view.frame = SNFRAME(10, 10 + i *HHHHEIGHT/2.0, HHHWIDTH-20, (HHHHEIGHT/2.0-10));
        [_footView addSubview:view];
        view.layer.cornerRadius = 5.0;
        view.layer.masksToBounds = YES;
        if (i == 0) {
            _view1 = view;
        }
        if (i == 1) {
            _view2 = view;
        }
        if (i == 2) {
            _view3 = view;
        }
        if (i == 3) {
            _view4 = view;
        }
    }
    
         [self loadSortStepView];
         [self loadSortSleepView];
         [self loadSortSleepView1];
         [self loadSortSleepView2];
}
//  模块1
- (void)loadSortStepView
{
    UILabel *info1 = [UILabel simpleWithRect:SNFRAME(0, 10, _view1.width, 20) withAlignment:NSTextAlignmentCenter withFontSize:15.0 withText:SN_Text(@"我的步数世界排名") withTextColor:SNCOLORBLACK];
    info1.adjustsFontSizeToFitWidth = YES;
    info1.font = SNFONT(17.0);
    [_view1 addSubview:info1];
    
    _stepView = [[SortStepView alloc] initWithFrame:SNFRAME(0, info1.bottom +10, _view1.width, (_view1.height - info1.bottom - 10)*0.80)];
    [_view1 addSubview:_stepView];
    
    [_stepView UpdateViewWithSortStep];
}
//  模块2
- (void)loadSortSleepView
{
    UILabel *info2 = [UILabel simpleWithRect:SNFRAME(0, 10, _view2.width, 20) withAlignment:NSTextAlignmentCenter withFontSize:15.0 withText:SN_Text(@"我的睡眠详情") withTextColor:SNCOLORBLACK];
    info2.font = SNFONT(17.0);
    [_view2 addSubview:info2];
    
    NSArray *segmentedArray = [NSArray arrayWithObjects:SN_Text(@"周平均"),SN_Text(@"月平均"),nil];
    UISegmentedControl *segCtl = [[UISegmentedControl alloc] initWithItems:segmentedArray];
    segCtl.frame = SNFRAME(_view2.width/4 -30, info2.bottom +20,_view2.width/2.0+60, 33);
    segCtl.selectedSegmentIndex = 0;
    segCtl.tintColor = [UIColor blackColor];
    [segCtl addTarget:self action:@selector(indexDidChangeForSegmentedControl:) forControlEvents:UIControlEventValueChanged];
    [_view2 addSubview:segCtl];
    [segCtl setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
    [segCtl setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateNormal];
    UIFont *font = [UIFont boldSystemFontOfSize:10.0f];
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
                                                           forKey:UITextAttributeFont];
    [segCtl setTitleTextAttributes:attributes
                               forState:UIControlStateNormal];
    
    _sleepView = [[SortSleepDetailView alloc]  initWithFrame:SNFRAME(0, segCtl.bottom +10, _view1.width, (_view2.height - segCtl.bottom - 10)*0.9)];
    [_view2 addSubview:_sleepView];
    [_sleepView UpdateViewWithType:SelectDateWeek];
}

// 睡眠质量模块
- (void)loadSortSleepView1
{
    UILabel *info2 = [UILabel simpleWithRect:SNFRAME(0, 10, _view2.width, 20) withAlignment:NSTextAlignmentCenter withFontSize:15.0 withText:SN_Text(@"我的睡眠质量世界排名") withTextColor:SNCOLORBLACK];
    info2.adjustsFontSizeToFitWidth = YES;
    info2.font = SNFONT(17.0);
    [_view3 addSubview:info2];
    
    _sleepInfoView1 = [[SortSleepView alloc] initWithFrame:SNFRAME(0, info2.bottom +10, _view3.width, (_view3.height - info2.bottom - 10)*0.80)];
    [_view3 addSubview:_sleepInfoView1];
    
    [_sleepInfoView1 UpdateViewWithType:SelectDateWeek withArray:@[@"1",@"2",@"3",@"4",@"4",@"3",@"2",@"1"] withCurrent:0 withSleepType:1];
}

// 入睡时间
- (void)loadSortSleepView2
{
    UILabel *info2 = [UILabel simpleWithRect:SNFRAME(0, 10, _view2.width, 20) withAlignment:NSTextAlignmentCenter withFontSize:15.0 withText:SN_Text(@"我的入睡时间世界排名") withTextColor:SNCOLORBLACK];
    info2.font = SNFONT(17.0);
    [_view4 addSubview:info2];
    
    _sleepInfoView2 = [[SortSleepView alloc] initWithFrame:SNFRAME(0, info2.bottom +10, _view4.width, (_view4.height - info2.bottom - 10)*0.80)];
    [_view4 addSubview:_sleepInfoView2];
    
    [_sleepInfoView2 UpdateViewWithType:SelectDateWeek withArray:@[@"4",@"3",@"2",@"1",@"1",@"2",@"3",@"4"] withCurrent:0 withSleepType:2];
}

-(void)indexDidChangeForSegmentedControl:(UISegmentedControl *)sender
{
    NSInteger selecIndex = sender.selectedSegmentIndex;
    if (selecIndex == 0) {
     [_sleepView UpdateViewWithType:SelectDateWeek];
    }
    else
    { [_sleepView UpdateViewWithType:SelectDateMonth];
    }
}

- (NSMutableAttributedString *)addattribtDic:(NSString*)text
{
    NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSMutableAttributedString *attribtStr ;
    if (text.length >0) {
      attribtStr = [[NSMutableAttributedString alloc]initWithString:text attributes:attribtDic];
    }
    return attribtStr;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"SortFriendListCell";
    SortFriendListCell  *cell       = [tableView cellForRowAtIndexPath:indexPath];
    
    if (nil == cell) {
        cell = [[SortFriendListCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    FriednInviterModel *model = _dataArray[indexPath.row];
    cell.tag = indexPath.row;
    [cell updateCellWithModel:model];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)functionSetLeft
{
    [self.navigationController popViewControllerAnimated:YES];
}
    
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
    [tabBar hiddenTheTabBarView];
    
    [SN_Net showHUD:SN_Text(@"加载 ...") withTime:1.0];
    
    DEF_WEAKSELF_(SNSortFriendVc)
    [SN_Net friendGetListSuccess:^(id object) {
    SHOWMBProgressHUDSTOP
        NSArray *listArray = object;
        if (listArray) {
            [weakSelf updateUIViewWith:listArray];
        }
    } fail:^(id object) {
    }];
    
    [self performSelector:@selector(delayGetSortFriend) withObject:nil afterDelay:0.1];
}

- (void)delayGetSortFriend
{
    // 步数分布更新
    DEF_WEAKSELF_(SNSortFriendVc)
    [SN_Net sortGetStepWithSuccess:^(id object) {
    [weakSelf.stepView UpdateViewWithSortStep];
    } fail:^(id object) {
        
    }];
    
    [SN_Net sortGetSleepTimeWithSuccess:^(id object) {
    [weakSelf.sleepInfoView1 UpdateViewWithType:SelectDateWeek withArray:@[@"1",@"2",@"3",@"4",@"4",@"3",@"2",@"1"] withCurrent:0 withSleepType:1];
    } fail:^(id object) {
        
    }];
    
    [SN_Net sortGetSleepStartTimeWithSuccess:^(id object) {
    [weakSelf.sleepInfoView2 UpdateViewWithType:SelectDateWeek withArray:@[@"1",@"2",@"3",@"4",@"4",@"3",@"2",@"1"] withCurrent:0 withSleepType:2];
    } fail:^(id object) {
        
    }];
}

- (void)updateUIViewWith:(NSArray *)listArray
{
    //    NSLog(@"更新好友列表>>>>>%@",listArray);
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (NSDictionary *dicN in listArray) {
        NSDictionary *dic = dicN[@"friend"];
        FriednInviterModel *model = [[FriednInviterModel alloc] init];
        model.userId = [dicN[@"friend_user_id"]integerValue];
        NSString *remark = dicN[@"remark"];
        if (remark.length == 0) {
            remark = SN_Text(@"未填写备注");
        }
        model.remark = remark;
        model.nickName = dic[@"nickname"];
        model.gender = [dic[@"gender"]integerValue];
        model.imagePathUrlString = dic[@"portrait"];
        model.sign = dic[@"sign"];
        NSDictionary *sport = dic[@"sport"];
        NSString *sportDateString = sport[@"today_date"];
        NSString *todayDateString = [[NSDate date]dateToDayString];
        if ([sportDateString isEqualToString:todayDateString]) {
            model.step = [sport[@"step"]integerValue];
            model.distance = [sport[@"distance"]integerValue];
            model.calory = [sport[@"calory"]integerValue];
            model.duration = [sport[@"duration"]integerValue];
        }
        else
        {
            model.step = 0;
            model.distance = 0;
            model.calory = 0;
            model.duration = 0;
        }
        
        [array addObject:model];
    }
    
    FriednInviterModel *myModel = [[FriednInviterModel alloc] init];
    myModel.userId = 10086;
    myModel.remark = SN_Text(@"未填写备注");
    myModel.nickName = SN_USER.nickName;
    myModel.gender = SN_USER.gender;
    myModel.imagePathUrlString = SN_USER.portrait;
    myModel.sign = SN_USER.sign;
    myModel.step = SN_PublicClass.todaySport.step;
    myModel.distance = SN_PublicClass.todaySport.distance;
    myModel.calory = SN_PublicClass.todaySport.calory;
    myModel.duration = SN_PublicClass.todaySport.stepDuration;
    [array addObject:myModel];
    
    NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        FriednInviterModel *model1 = (FriednInviterModel *)obj1;
        FriednInviterModel *model2 = (FriednInviterModel *)obj2;
        return [StrByInt(model2.step) compare:StrByInt(model1.step)];
    }];
    _dataArray = [NSMutableArray array];
    for (int i = 0; i <sortArray.count; i++) {
        FriednInviterModel *model = [sortArray objectAtIndex:i];
        if ([SN_USER.nickName isEqualToString: model.nickName]) {
            _label2.text = [NSString stringWithFormat:@"%d  ",i+1];
            _label2.attributedText = [self addattribtDic:_label2.text];
        }
        if (i< 5) {
            FriednInviterModel *model = [sortArray objectAtIndex:i];
            [_dataArray addObject:model];
        }
    }
    [_tableView reloadData];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
